package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import io.seata.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service

public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Autowired
    ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto dto) {
        //1.校验参数 手机编码、手机号、密码
        if (dto.getEquipmentId() == null && StringUtils.isBlank(dto.getPhone()) && StringUtils.isBlank(dto.getPhone())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.执行业务
        //查询用户 登陆
        if (StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())){
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery()
                    .eq(ApUser::getPhone, dto.getPhone()));

            if (apUser ==null ){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "请检查手机号");
            }
            //对比密码
            String dbpassword = apUser.getPassword();//数据库密码
            String password = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
            System.out.println(password);
            if (!dbpassword.equals(password)){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "手机号或密码错误");
            }
            //添加token
            Map<String, Object> map = new HashMap<>();
            apUser.setPassword("");
            apUser.setSalt("");
            map.put("apUser",apUser);
            map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
            return ResponseResult.okResult(map);

        }else {//不登陆
            //添加token
            //添加token
            Map<String, Object> map = new HashMap<>();

            map.put("token", AppJwtUtil.getToken(dto.getEquipmentId().longValue()));
            return ResponseResult.okResult(map);
        }

    }
}
